/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package com.dhpollack.rotogss.servlets;

import java.io.IOException;
import java.util.LinkedHashSet;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;

import com.dhpollack.rotogss.data.AppConfig;
import com.dhpollack.rotogss.data.RotoGSSUsers;
import com.dhpollack.rotogss.data.RotoGSSTeams;
import com.dhpollack.rotogss.helper.AppHelper;
import com.dhpollack.rotogss.helper.PMF;

/**
 * @author davidpl
 *
 */
public class GoogleOAuthReturnServlet extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7008686382376745044L;

	protected void service(HttpServletRequest req, HttpServletResponse resp)
	throws ServletException, IOException {
		
		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
        if (user != null) {
        	
        	AppConfig appConfig = AppHelper.get();
        	
    		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
    		oauthParameters.setOAuthConsumerKey(appConfig.getGoogleConsumerKey());
    		oauthParameters.setOAuthConsumerSecret(appConfig.getGoogleConsumerSecret());
        
    		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
    		oauthHelper.getOAuthParametersFromCallback(req.getQueryString(), oauthParameters);
    				
    		try {
    			String accessToken = oauthHelper.getAccessToken(oauthParameters);
    			String accessTokenSecret = oauthParameters.getOAuthTokenSecret();
    	        Transaction tx = pm.currentTransaction();
    	        try {
    	        	tx.begin();
    	            Key userkey = KeyFactory.createKey(RotoGSSUsers.class.getSimpleName(),user.getNickname());
    	            RotoGSSUsers rotouser;
    	            try {
    	            	log("Find User");
    	                rotouser = pm.getObjectById(RotoGSSUsers.class, userkey);
    	            } catch(JDOObjectNotFoundException e) {
    	            	log("User Not Found.  Being Created...");
    	            	rotouser = new RotoGSSUsers();
    	            	rotouser.setGoogleUserKey(userkey);
    	            	rotouser.setYahooGamesTracked(new LinkedHashSet<Key>());
    	            	rotouser.setYahooTeamsTracked(new LinkedHashSet<RotoGSSTeams>());
    	            }
    	            if(accessToken.length() > 1) {
        	            rotouser.setGoogleAccessToken(accessToken);
    	            } else {
    	            	log("Access Token too short\nAccess Token: " + accessToken);
    	            }
    	            if(accessTokenSecret.length() > 1) {
        	            rotouser.setGoogleAccessTokenSecret(accessTokenSecret);
    	            } else {
    	            	log("Access Token Secret too short\nAccess Token Secret: " + accessTokenSecret);
    	            }
    	        	pm.makePersistent(rotouser);
    	        	tx.commit();
    	        } finally {
    	        	if(tx.isActive()) {
    	        		tx.rollback();
    	        	}
    	        }
    	        
    	        resp.sendRedirect("/start.jsp");
    		} catch (OAuthException e) {
    			// TODO Auto-generated catch block
    			log("OAuthException");
    			e.printStackTrace();
    		}
        }
	}
}
